package com.rul.mars.common.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.rul.mars.common.service.SendSmsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 发送手机短信服务
 *
 * @author RuL
 */
@Component
public class SendSmsServerImpl implements SendSmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.product}")
    private String product;
    @Value("${aliyun.sms.domain}")
    private String domain;
    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.connectTimeout.key}")
    private String connectTimeoutKey;
    @Value("${aliyun.sms.connectTimeout.value}")
    private String connectTimeoutValue;
    @Value("${aliyun.sms.readTimeout.key}")
    private String readTimeoutKey;
    @Value("${aliyun.sms.readTimeout.value}")
    private String readTimeoutValue;

    /**
     * 发送手机短信验证码
     *
     * @param phone    手机号
     * @param authCode 手机验证码
     * @return 短信发送是否成功
     */
    @Override
    public boolean sendAuthCode(String phone, String authCode) throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty(connectTimeoutKey, connectTimeoutValue);
        System.setProperty(readTimeoutKey, readTimeoutValue);

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //待发送的手机号
        request.setPhoneNumbers(phone);
        //短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_212701291");
        //短信模板参数
        request.setTemplateParam("{\"authCode\":\"" + authCode + "\"}");

        SendSmsResponse sendSmsResponse = null;
        sendSmsResponse = acsClient.getAcsResponse(request);

        //请求成功与否
        return sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK");
    }
}
